package com.fancon.android.gardenjokesx.activity;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.RelativeLayout;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.social.BaseRequestListener;
import com.fancon.android.gardenjokesx.social.DatabaseHelper;
import com.fancon.android.gardenjokesx.social.Keys;
import com.fancon.android.gardenjokesx.social.SessionEvents;
import com.fancon.android.gardenjokesx.social.SessionEvents.AuthListener;
import com.fancon.android.gardenjokesx.social.SessionEvents.LogoutListener;
import com.fancon.android.gardenjokesx.social.SessionStore;
import com.fancon.android.gardenjokesx.social.Utility;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask;
import com.fancon.android.gardenjokesx.utils.DownloadImageTask.IExcuteUi;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;

public class S03_2Activity extends GardenJokesBaseActivity {

	private RelativeLayout topBar;
	private int screenID;
	private Bundle bund;
	private String isSignIn;
	private int pre_screen_id;
	//
	private String url_img="";
	final static int AUTHORIZE_ACTIVITY_RESULT_CODE = -1;
	String[] permissions = { "offline_access", "publish_stream", "user_photos",
			"publish_checkins", "photo_upload", "user_relationship_details",
			"user_birthday", "email", "user_location" };

	private SessionListener mSessionListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.s03_1_2_3_4_7);
		try {
			CookieSyncManager.createInstance(this);
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.removeAllCookie();
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		if (getIntent().getExtras() != null) {
			bund = getIntent().getExtras();
			screenID = bund.getInt(Constant.SCREEN_ID);
			Log.d("Screen ID", Integer.toString(screenID));
			pre_screen_id = getIntent().getExtras().getInt(
					Constant.PRE_SCREEN_ID);
			isSignIn = getIntent().getExtras().getString(Constant.IS_SIGNIN);
		}

		// set Backgroud cho Top Bar
		topBar = (RelativeLayout) findViewById(R.id.s03_12347_bg_top);
		topBar.setVisibility(View.GONE);

		connectFacebook();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			bund.putBoolean(Constant.LINK_STATE, false);
			finishAc();
		}
		return (super.onKeyDown(keyCode, event));
	}

	/*
	 * The Callback for notifying the application when authorization succeeds or
	 * fails.
	 */

	public class FbAPIsAuthListener implements AuthListener {

		@Override
		public void onAuthSucceed() {
			requestUserData();
		}

		@Override
		public void onAuthFail(String error) {
			Log.v("Login Failed:", error);
		}
	}

	/*
	 * The Callback for notifying the application when log out starts and
	 * finishes.
	 */
	public class FbAPIsLogoutListener implements LogoutListener {
		@Override
		public void onLogoutBegin() {
			Log.v("Logging out...", "Logging out...");
		}

		@Override
		public void onLogoutFinish() {
			Log.v("You have logged out!", "You have logged out!");
		}
	}

	/*
	 * Request user name, and picture to show on the main screen.
	 */
	public void requestUserData() {

		Bundle params = new Bundle();
		params.putString("fields", "name, picture");

		try {
			String resp = Utility.mFacebook.request("me", params, "GET");
			Log.d("JsonRequest", resp);
			JSONObject jsonObject = new JSONObject(resp);

			Utility.userNameFB = jsonObject.getString("name");
			Utility.userUID = jsonObject.getString("id");
			url_img = jsonObject.getString("picture");
			jsonObject = null;

		} catch (FileNotFoundException e) {
			Log.e("FileNotFoundException", e.getMessage());
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException", e.getMessage());
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
		} catch (JSONException e) {
			Log.e("JSONException", e.getMessage());
		}
	}

	private class SessionListener implements AuthListener, LogoutListener {

		@Override
		public void onAuthSucceed() {
			SessionStore.save(Utility.mFacebook,
					S03_2Activity.this.getApplicationContext());
		}

		@Override
		public void onAuthFail(String error) {
		}

		@Override
		public void onLogoutBegin() {
		}

		@Override
		public void onLogoutFinish() {
			SessionStore.clear(S03_2Activity.this.getApplicationContext());
		}
	}

	private final class LoginDialogListener implements DialogListener {
		@Override
		public void onComplete(Bundle values) {
			SessionEvents.onLoginSuccess();

			User userID = new User();
			userID = UserUtil.getInfoUserLogin(S03_2Activity.this);

			if (userID.getUser_id() != null && userID.getUser_id().length() > 0) {
				RegisterLinkReq resgister = new RegisterLinkReq(
						"register_link", S03_2Activity.this,
						userID.getUser_id(), Utility.userUID, "F",
						Utility.mFacebook.getAccessToken(), false);
				getGlobalState().getRequestQueue().addRequest(resgister);
				// registerLink(userID.getUser_id(), Utility.userUID, "F",
				// Utility.mFacebook.getAccessToken(), false);
			}

			if (screenID == Constant.A02_2 || (screenID == Constant.S06 && pre_screen_id == Constant.S01)) {
				Bundle b = new Bundle();
				if (screenID == Constant.S06) {
					b = getIntent().getExtras();
				}
				final Bundle bx = b;
				// binhbt comment

				//@binint added
				IExcuteUi ie = new IExcuteUi() {

					@Override
					public void preExecute() {
						// TODO Auto-generated method stub

					}

					@Override
					public void execute() {
						// TODO Auto-generated method stub

					}

					@Override
					public void executeUI(String realPath) {
						// TODO Auto-generated method stub

						Intent inten = new Intent(getApplicationContext(),
								SignupActivity.class);
						inten.putExtras(bx);
						inten.putExtra(Constant.SCREEN_ID, Constant.S03_2);
						inten.putExtra(Constant.FACEBOOK_ACCESS_TOKEN,
								Utility.mFacebook.getAccessToken());
						inten.putExtra(Constant.URL_IMAGE, realPath);
						//
						startActivity(inten);
						finish();
					}

				};
				
				DownloadImageTask photoReq = new DownloadImageTask("photo_rq", S03_2Activity.this, url_img);
				photoReq.setIe(ie);
				getGlobalState().getRequestQueue().addRequest(photoReq);
				//


			} else {
				DatabaseHelper db = new DatabaseHelper(S03_2Activity.this);
				db.addFacebookUser(userID.getUser_id(), Utility.userUID,
						Utility.mFacebook.getAccessToken(), Utility.userNameFB);
				db.close();
				bund.putBoolean(Constant.LINK_STATE, true);
			}
			finishAc();
		}

		@Override
		public void onFacebookError(FacebookError error) {
			SessionEvents.onLoginError(error.getMessage());
			bund.putBoolean(Constant.LINK_STATE, false);
			finishAc();
		}

		@Override
		public void onError(DialogError error) {
			SessionEvents.onLoginError(error.getMessage());
			bund.putBoolean(Constant.LINK_STATE, false);
			finishAc();
		}

		@Override
		public void onCancel() {
			SessionEvents.onLoginError("Action Canceled");
			bund.putBoolean(Constant.LINK_STATE, false);
		}
	}

	public void connectFacebook() {
		if (screenID == Constant.A02_2) {
			signOutFB();
		}
		Log.d("Connect", "Connect S032");
		// Create the Facebook Object using the app id.
		Utility.mFacebook = new Facebook(Keys.APP_ID);

		// Instantiate the asynrunner object for asynchronous api calls.
		Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);

		// restore session if one exists
		SessionEvents.addAuthListener(new FbAPIsAuthListener());
		SessionEvents.addLogoutListener(new FbAPIsLogoutListener());

		mSessionListener = new SessionListener();
		SessionEvents.addAuthListener(mSessionListener);
		SessionEvents.addLogoutListener(mSessionListener);
		// if (S03_2Activity.this.getParent() == null) {
		Utility.mFacebook.authorize(S03_2Activity.this, permissions,
				AUTHORIZE_ACTIVITY_RESULT_CODE, new LoginDialogListener());
		// } else {
		// @binhbt comment

		// MeshGroupActivity activityStack = (MeshGroupActivity)
		// S03_2Activity.this
		// .getParent();
		// Utility.mFacebook.authorize(S03_2Activity.this, permissions,
		// AUTHORIZE_ACTIVITY_RESULT_CODE, new LoginDialogListener());

		// }

	}

	public void signOutFB() {
		if (Utility.mFacebook != null
				&& Utility.mFacebook.getAccessToken() != null) {
			Log.w("LOG OUT FB", "LOUT FB");
			SessionEvents.onLogoutBegin();
			AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(
					Utility.mFacebook);
			asyncRunner.logout(S03_2Activity.this, new LogoutRequestListener());
		}
	}

	private class LogoutRequestListener extends BaseRequestListener {
		@Override
		public void onComplete(String response, final Object state) {
			SessionEvents.onLogoutFinish();
		}
	}

	public void finishAc() {

		switch (screenID) {
		case Constant.S03:
			// @binhbt comment
			 Intent ii = new
			 Intent(S03_2Activity.this.getApplicationContext(), S03Activity.class); 
			 ii.putExtra(Constant.IS_SIGNIN, isSignIn);
			 startActivity(ii); finish();
			 
			break;

		case Constant.M01_1:
			Intent i = getIntent();
			i.putExtras(bund);
			setResult(RESULT_OK, i);
			finish();
			break;

		case Constant.P06:
			Intent in = getIntent();
			in.putExtras(bund);
			setResult(RESULT_OK, in);
			finish();
			break;

		case Constant.M04_7:
			Intent intent = getIntent();
			intent.putExtras(bund);
			setResult(RESULT_OK, intent);
			finish();
			break;

		case Constant.S07:
			Intent inn = getIntent();
			inn.putExtras(bund);
			setResult(RESULT_OK, inn);
			finish();
			break;

		case Constant.S02:
			// @binhbt comment
			/*
			 * Intent iii = new Intent(S03_2Activity.this, S02Activity.class);
			 * iii.putExtras(bund); iii.putExtra(Constant.SCREEN_ID,
			 * Constant.S03_2); iii.putExtra(Constant.FACEBOOK_ACCESS_TOKEN,
			 * Utility.mFacebook.getAccessToken()); startActivity(iii);
			 * finish();
			 */
			break;

		case Constant.S06:
			if (pre_screen_id == Constant.U02) {
				if (Utility.mFacebook != null
						&& Utility.mFacebook.getAccessToken() != null
						&& Utility.mFacebook.getAccessToken().length() > 0) {
					String urlProfile = "https://graph.facebook.com/"
							+ Utility.userUID + "/picture?type=large";
					//ImageLoader imageLoader = ((IMeshCache) S03_2Activity.this)
					//		.getmImgLoader();
					//String imageProfileUrl = imageLoader
					//		.getImageFromSD(urlProfile);
					//Log.d("S03_2", "profile url:  " + imageProfileUrl);

					//
					//@binhbt added
					IExcuteUi ie = new IExcuteUi() {

						@Override
						public void preExecute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void execute() {
							// TODO Auto-generated method stub

						}

						@Override
						public void executeUI(String realPath) {
							// TODO Auto-generated method stub
							Log.d("S03_2", "profile url:  " + realPath);
							Bitmap bm = BitmapFactory.decodeFile(realPath);

							ByteArrayOutputStream bos = new ByteArrayOutputStream();
							bm.compress(CompressFormat.JPEG, 100, bos);
							byte[] data = bos.toByteArray();
							ByteArrayBody bad = new ByteArrayBody(data, "avatar.jpg");
							MultipartEntity reqEntity = new MultipartEntity();
							String user_id = UserUtil.getInfoUserLogin(
									S03_2Activity.this).getUser_id();
							try {
								reqEntity.addPart("image", bad);
								reqEntity.addPart("user_id", new StringBody(user_id));
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							//@binhbt-comment
							//upload downloaded image to server
							//must use another thread to enhance process
							GardenJokesApiConnect apiConnect = new GardenJokesApiConnect(S03_2Activity.this);
							String result = apiConnect
									.execPostImg(S03_2Activity.this,
											GardenJokesApiConnect.GROUP_S, "updateImageProfile",
											reqEntity);
							Log.d("S03_1", "post result: " + result);
							finish();
						}

					};
					
					DownloadImageTask photoReq = new DownloadImageTask("photo_rq", S03_2Activity.this, urlProfile);
					photoReq.setIe(ie);
					getGlobalState().getRequestQueue().addRequest(photoReq);
					
				}
			} else {
				finish();
			}
			break;

		case Constant.S04:
			// @binhbt comment
				Intent s04Intent = new Intent(S03_2Activity.this,
						S041Activity.class);
				s04Intent.putExtra(Constant.SCREEN_ID, Constant.S03_2);
				s04Intent.putExtra(Constant.ID_BUTTON, "btnFB");
				startActivity(s04Intent);
				finish();
			break;

		case Constant.U03:
			
			  EditYouElementActivity.fromFacebook = true;
			  finish();
			 
		default:
			finish();
			break;
		}
	}

	public void registerLink(String user_id, String id, String type,
			String token, Boolean is_cancel) {
		List<NameValuePair> request = new ArrayList<NameValuePair>(6);
		request.add(new BasicNameValuePair("user_id", user_id));
		request.add(new BasicNameValuePair("id", id));
		request.add(new BasicNameValuePair("type", type));
		request.add(new BasicNameValuePair("token", token));
		request.add(new BasicNameValuePair("secret", ""));
		if (is_cancel == false) {
			request.add(new BasicNameValuePair("is_cancel", "0"));
		} else {
			request.add(new BasicNameValuePair("is_cancel", "1"));
		}
		try {
			GardenJokesApiConnect api = new GardenJokesApiConnect(
					S03_2Activity.this);
			String req = api.execPost(S03_2Activity.this,
					GardenJokesApiConnect.GROUP_S,
					"registerLinkToOtherServices", request);
			if (req != null && req.length() > 0) {
				Log.d("S03_2 registerLinkToOtherServices", req);
			}
		} catch (Exception e) {
		}

	}

	class RegisterLinkReq extends RequestUI {
		private String user_id, id, type, token;
		private Boolean is_cancel;

		public RegisterLinkReq(Object key, Activity activity, String user_id,
				String id, String type, String token, Boolean is_cancel) {
			super(key, activity);
			this.user_id = user_id;
			this.id = id;
			this.type = type;
			this.token = token;
			this.is_cancel = is_cancel;
			// TODO Auto-generated constructor stub
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub

		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			registerLink(user_id, id, type, token, is_cancel);
		}

	}
}
